package case5

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

func Test() {

	fmt.Println("🎯示例五：操作新增数据")
	db, err := mysqlConnect()
	if err != nil {
		fmt.Println("connect fail", err)
	}

	if err := db.AutoMigrate(&UserCase5{}); err != nil {
		fmt.Println("自动创建表失败：", err)
		return
	}

	fmt.Println("创建表成功...")
	uc1 := UserCase5{UserName: "zhagnsan", PassWord: "123", Age: 22, State: "正常"}
	fmt.Println(uc1)
	// 插入数据
	db.Create(&uc1) //使用指针来创建
	fmt.Println("返回插入数据主键id：", uc1.ID)

	// 批量插入
	ucArr1 := []UserCase5{
		{UserName: "lisi", PassWord: "123", State: "正常"},
		{UserName: "xm", PassWord: "123", State: "冻结"},
	}
	db.Create(&ucArr1)

	//// 选择字段创建
	//db.Select("UserName", "PassWord").Create(&uc1)

	//// 忽略字段创建
	//db.Omit("Age").Create(&uc1)

}

// 初始化连接
func mysqlConnect() (*gorm.DB, error) {
	url := "root:123456@tcp(127.0.0.1:3306)/case1?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(url), &gorm.Config{})
	if err != nil {
		return nil, fmt.Errorf("连接数据库失败：", err)
	}
	return db, nil
}

// 创建表结构
type UserCase5 struct {
	ID         int        `gorm:"primarykey;autoIncrement"` //id自增
	UserName   string     `gorm:"type:varchar(20);not null;unique"`
	PassWord   string     `gorm:"type:varchar(20);not null"`
	Sex        bool       `gorm:"type:tinyint(1);default:true"`
	Age        int        `gorm:"type:int(11);"`
	State      string     `gorm:"type:varchar(20);"`
	CreateTime time.Time  `gorm:"type:datetime;autoCreateTime"`            //自动设置创建时间
	UpdateTime time.Time  `gorm:"type:datetime;default:CURRENT_TIMESTAMP"` //设置默认值
	OptionTime *time.Time `gorm:"type:datetime;"`                          //操作时间
	// 操作时间不能为空 Error 1292 (22007): Incorrect datetime value: '0000-00-00' for column 'option_time' at row 1
	// 解决方式：使用指针运行为null, 或者设置默认值 ：default:CURRENT_TIMESTAMP ！
}
